<template>
  <el-form class="search-from" :model="form" label-width="auto" ref="formRef" style="max-width: 100%">
    <el-row :gutter="80">
      <template v-for="item in _list" :key="item">
        <el-col :span="8" v-if="item.isShow === 'true' || !item.isShow">
          <el-form-item
            :label="item?.label"
            :label-width="item?.labelWidth ? item?.labelWidth : 85"
            :prop="item?.type === 'select-input' ? item.model.split('-')[1] : item.model"
            :rules="item.required ? { required: true, message: '请输入', trigger: ['blur'] } : []"
          >
            <!-- 输入框 -->
            <el-input
              v-if="item?.type === 'input'"
              v-model="form[item.model]"
              :placeholder="item['placeholder'] ? item['placeholder'] : '请输入'"
            />
            <!-- 下拉选择框 -->
            <el-select
              v-else-if="item?.type === 'select'"
              clearable
              v-model="form[item.model]"
              :placeholder="item['placeholder'] ? item['placeholder'] : '请选择'"
              style="width: 100%"
            >
              <el-option
                v-for="_item in item?.data"
                :key="_item.value"
                :label="item.props ? _item[item.props.label] : _item.label"
                :value="item.props ? _item[item.props.value] : _item.value"
                :disabled="_item.disabled"
              />
            </el-select>
            <!-- 树型下拉 -->
            <el-tree-select
              v-else-if="item?.type === 'select-tree'"
              clearable
              v-model="form[item.model]"
              :node-key="item.nodeKey"
              check-strictly
              default-expand-all
              :data="item.data"
              :render-after-expand="false"
              :props="{
                label: 'name'
              }"
              style="width: 100%"
            />
            <!-- @node-click="handleNodeClick" -->
            <!-- 日期范围选择 -->
            <el-date-picker
              v-else-if="item?.type === 'daterange'"
              clearable
              v-model="form[item.model]"
              type="daterange"
              range-separator=" - "
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD  HH:mm:ss"
              :placeholder="item['placeholder'] ? item['placeholder'] : '请选择'"
              @change="daterangeChange"
            />
            <!-- 单个日期选择 -->
            <el-date-picker
              v-else-if="item?.type === 'date'"
              clearable
              v-model="form[item.model]"
              type="date"
              :format="item['format'] ? item['format'] : 'YYYY-MM-DD'"
              :value-format="item['valueFormat'] ? item['valueFormat'] : 'YYYY-MM-DD'"
              :placeholder="item['placeholder'] ? item['placeholder'] : '请选择'"
              style="width: 100%"
            />
            <!-- 价格范围选择 -->
            <div v-else-if="item?.type === 'numrange'" class="numrange">
              <el-input-number v-model="form[item.model.split('-')[0]]" :min="0" :controls="false" />
              <span> - </span>
              <el-input-number v-model="form[item.model.split('-')[1]]" :min="0" :controls="false" />
            </div>

            <!-- 省市区级联选择 -->
            <el-cascader
              v-else-if="item?.type === 'city-select'"
              v-model="form[item.model]"
              :options="area"
              :props="item.props"
              collapse-tags
              collapse-tags-tooltip
              :max-collapse-tags="1"
              style="width: 100%"
            />

            <!-- 下拉级联选择 -->
            <el-cascader
              v-else-if="item?.type === 'cascader'"
              v-model="form[item.model]"
              :options="item.data || []"
              :props="item.props"
              clearable
              collapse-tags
              collapse-tags-tooltip
              :max-collapse-tags="1"
              style="width: 100%"
            />

            <!-- 输入框嵌入下拉选择 -->
            <el-input
              class="jzt-select-input"
              v-else-if="item?.type === 'select-input'"
              v-model="form[item.model.split('-')[1]]"
              style="max-width: 600px"
              :placeholder="item.placeholder || '请输入'"
              :disabled="!(form[item.model.split('-')[0]] || form[item.model.split('-')[0]] == 0)"
            >
              <template #prepend>
                <el-select v-model="form[item.model.split('-')[0]]" :placeholder="'请选择'" style="width: 100px">
                  <el-option
                    v-for="_item in item?.data"
                    :key="_item.value"
                    :label="item.props ? _item[item.props.label] : _item.label"
                    :value="item.props ? _item[item.props.value] : _item.value"
                  />
                </el-select>
                <!-- <el-cascader
                  v-model="form[item.model.split('-')[0]]"
                  :show-all-levels="true"
                  :options="item.data"
                  @change="form[item.model.split('-')[1]] = ''"
                /> -->
              </template>
              <template #append>
                <!-- <el-button :icon="Search" /> -->
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </template>
      <el-col :span="8" v-if="colBtn" style="display: flex">
        <el-button type="primary" :icon="Search" @click="submit">查询</el-button>
        <el-button type="primary" plain :icon="RefreshRight" @click="reset">重置</el-button>
      </el-col>
    </el-row>
  </el-form>
  <div class="btn-wrap" v-if="!colBtn">
    <el-button type="primary" :icon="Search" @click="submit">查询</el-button>
    <el-button type="primary" plain :icon="RefreshRight" @click="reset">重置</el-button>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import { Search, RefreshRight } from "@element-plus/icons-vue";
import { getArea } from "@/api/index.js";

const area = ref([]);
const _list = ref([]);
const form = ref({});
const formRef = ref();

const props = defineProps({
  list: {
    type: Array,
    default: () => []
  },
  colBtn: {
    //是否把操作按钮放在col标签内，默认false
    type: Boolean,
    default: false
  }
});
const emit = defineEmits(["submit", "reset", "daterangeChange"]);
onMounted(() => {
  // 如果有省市区搜索条件，调接口
  if (
    props.list.some(item => {
      return item.type === "city-select";
    })
  ) {
    getArea().then(res => {
      area.value = res.data;
    });
  }
});

watch(
  () => props.list,
  async val => {
    _list.value = JSON.parse(JSON.stringify(props.list));
  },
  { deep: true, immediate: true }
);

const submit = () => {
  formRef.value.validate((valid, fields) => {
    if (valid) {
      const formData = JSON.parse(JSON.stringify(form.value));
      emit("submit", formData);
    } else {
      console.log("error submit!", fields);
    }
  });
};

const setFormData = (model, val) => {
  form.value[model] = val;
};

const reset = () => {
  formRef.value.resetFields();
  for (let item of props.list) {
    if (item.type === "numrange" || item.type === "select-input") {
      form.value[[item.model.split("-")[0]]] = undefined;
      form.value[[item.model.split("-")[1]]] = undefined;
    } else {
      form.value[item.model] = null;
    }
  }
  emit("reset");
};

const daterangeChange = arr => {
  //如果日期范围组件，开始时间和结束时间完全一致，结束时间统一更改为 23:59:59
  if (arr[0] === arr[1]) {
    arr[1] = arr[0].split(" ")[0] + " 23:59:59";
  }
  emit("daterangeChange");
};

defineExpose({ setFormData });
</script>

<style scoped lang="scss">
.search-from {
  overflow: hidden;
  ::v-deep(.el-input-group--prepend .el-input-group__prepend .el-select .el-select__wrapper) {
    box-shadow: none !important;
  }
  ::v-deep(.el-input__wrapper) {
    background-color: white !important;
  }
  ::v-deep(.el-select__wrapper) {
    background-color: white !important;
  }
  ::v-deep(.el-date-editor.el-input__wrapper) {
    box-shadow: 0 0 0 1px white inset !important;
  }

  ::v-deep(.el-input.is-disabled .el-input__inner) {
    -webkit-text-fill-color: #a8abb2;
  }
  ::v-deep(.el-input-group__append) {
    padding: 0 !important;
  }
  ::v-deep(.el-icon.el-input__icon.el-input__validateIcon) {
    display: none;
  }
  // ::v-deep(.el-input-group__prepend) {
  //   padding: 0;
  //   box-shadow: none;
  // }
  // ::v-deep(.el-input.el-input-group.el-input-group--append.el-input-group--prepend) {
  //   & > .el-input-group__prepend {
  //     border-radius: 4px 0 0 4px;
  //     border: 1px solid #dcdfe6;
  //     border-right: none;
  //     .el-input__wrapper {
  //       border-radius: 4px;
  //     }
  //     .el-cascader.el-tooltip__trigger.el-tooltip__trigger {
  //       border-radius: 4px 0 0 4px;
  //     }
  //   }
  //   & > .el-input__wrapper {
  //     border: 1px solid #dcdfe6;
  //   }
  // }
  // ::v-deep(.el-input__wrapper) {
  //   box-shadow: none;
  // }

  .numrange {
    width: 100%;
    display: flex;
    justify-content: space-between;

    .el-input-number {
      flex: 1;
    }

    span {
      width: 30px;
      text-align: center;
    }
  }
}

.btn-wrap {
  display: flex;
  justify-content: flex-end;
}
</style>
